<?php


namespace App\Http\Controllers\Admin;
use App\Http\Controllers\BaseController;
use App\Models\Merchant;
use App\Models\ProducerAdv;
use Illuminate\Http\Request;

class ProducerController extends BaseController
{
    public $model = Merchant::class;
    /**
     * 列表
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request) {
        $search = [ 'phone' => '', 'audit_status' => -1
            , 'start_at' => null, 'end_at' => null];
        $input = $request->input();
        $fac_title = $request->input('fac_title');
        $list = Merchant::where('category', 2)->when($fac_title, function ($q) use($fac_title){
            $q->where('fac_title', 'like', '%' . $fac_title . '%');
        })->apply($search, $input)->orderBy("id", "desc")
            ->paginate(\request('per_page', 20));
        return $this->paginate($list);
    }


    public function store(Request $request) {
        $input = $request->input();
        $this->validate($request, [
            'phone'  => 'required',
        ]);

        $id = \request('id');
        $exist_id = ProducerAdv::where('phone', \request('phone'))
            ->whereIn('audit_status', [0, 1])->value('id');
        if ($id) {
            if ($exist_id && ($id != $exist_id)) {
                return $this->failed("手机号已经存在");
            }
            ProducerAdv::where('id', $id)->update($input);
        } else {
            if ($exist_id)
                return $this->failed("手机号已经存在");

            $input['raw_password'] = create_password(6);
            $input['password'] = bcrypt($input['raw_password']);
            $admin = ProducerAdv::create($input);
            $id = $admin->id;
        }
        return $this->success(['id' => $id]);
    }



}

